package com.xy.servicemanage.request;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VerifyCodeHelper {
	private static VerifyCodeHelper me=new VerifyCodeHelper();
	private static final Logger log = LoggerFactory
			.getLogger(VerifyCodeHelper.class);
	private static Map<String, VerfiyObject> codeMap=new HashMap<String, VerifyCodeHelper.VerfiyObject>();

	public static String sendMessage(Map vmap) {
		String phoneno = (String)vmap.get("phoneNo");
		int code = new Random().nextInt(100000);
		String msg = "to=" + phoneno + "&message=尊敬的用户，请在平安E通输入以下登陆验证码 :" + code + " ";
		try {
			send(msg);
		} catch (Exception e) {
			log.error("sendMessage", e);
		}
		VerfiyObject v=me.new VerfiyObject(phoneno,String.valueOf(code));
		codeMap.put(phoneno, v);
		
		return String.valueOf(code);
	}

	public static int verify(Map  vmap) {
		String phone = (String)vmap.get("LoginName");
		String code =  (String)vmap.get("PWD");
		VerfiyObject v = codeMap.get(phone);
		int r = 0;
		if (v != null && v.getCode().equals(code)
				&& (System.currentTimeMillis() - v.getCreatetime() < 60000)) {
			r = 1;
		}
		return r;
	}
	public static String send(String msg) throws Exception {
		String u = "http://10.43.129.4/websend_jzxt.jsp";
		URL url = new URL(u);
		URLConnection conn = url.openConnection();
		conn.setDoOutput(true);
		conn.setRequestProperty("User-Agent", "MSIE");
		conn.connect();
		OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
		wr.write(new String(msg.getBytes("GBK")));
		wr.flush();
		BufferedReader rd = new BufferedReader(new InputStreamReader(
				conn.getInputStream()));
		String line;
		StringBuffer sb = new StringBuffer();
		while ((line = rd.readLine()) != null) {
			sb.append(line);
		}
		wr.close();
		rd.close();
		return sb.toString();
	}

	class VerifyThread implements Runnable {
		@Override
		public void run() {
			// TODO Auto-generated method stub

		}
	}

	class VerfiyObject {
		private String phone;
		private String code;
		private long createtime;

		public VerfiyObject(String p,String c) {
		 this.phone=p;
		 this.code=c;
		 this.createtime=System.currentTimeMillis();
		}
		public String getPhone() {
			return phone;
		}

		public void setPhone(String phone) {
			this.phone = phone;
		}

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}

		public long getCreatetime() {
			return createtime;
		}

		public void setCreatetime(long createtime) {
			this.createtime = createtime;
		}
	}
}
